package quiz;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/Login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher dpatch = request.getRequestDispatcher("login.jsp");
		dpatch.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletContext ctxt = request.getServletContext();
		DataBase db = (DataBase)ctxt.getAttribute("db");
				
		Account.setDataBase(db);
		Account acct = db.getAccountByUsername((String)request.getParameter("username"));	
		if (acct != null && acct.passwordMatch((String)request.getParameter("password"))) {
			HttpSession session = request.getSession();
			session.setAttribute("account", acct);
			response.sendRedirect("Profile");
		} else {
			request.setAttribute("error", "The parts you provided us just do not seem to fit together.  Better luck next time!");
			
			RequestDispatcher dpatch = request.getRequestDispatcher("login.jsp");
			dpatch.forward(request, response);
		}	
		
	}

}
